﻿namespace Leetcode.N0008;

public class Solution
{
    public int MyAtoi(string s)
    {
        int result = 0;
        bool hasNumber = false;
        bool isNegativeNumber = false;
        bool hasError = false;
        for (int i = 0; i < s.Length; i++)
        {
            var letter = s[i];
            switch (letter)
            {
                case ' ':
                    hasError = hasNumber;
                    break;
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    hasNumber = true;
                    int value;
                    if (isNegativeNumber)
                    {
                        value = -(letter - '0');
                        if (int.MinValue / 10 > result)
                        {
                            return int.MinValue;
                        }
                        else if (int.MinValue - result * 10 > value)
                        {
                            return int.MinValue;
                        }
                    }
                    else
                    {
                        value = (int)(letter - '0');
                        if (int.MaxValue / 10 < result)
                        {
                            return int.MaxValue;
                        }
                        else if (int.MaxValue - result * 10 < value)
                        {
                            return int.MaxValue;
                        }
                    }

                    result = result * 10 + value;
                    break;
                case '-':
                    hasError = hasNumber;
                    hasNumber = true;
                    isNegativeNumber = true;
                    break;
                case '+':
                    hasError = hasNumber;
                    hasNumber = true;
                    isNegativeNumber = false;
                    break;
                default:
                    hasError = true;
                    break;
            }
            if (hasError)
            {
                return result;
            }
        }
        return result;
    }
}
